package com.company.account.controller;

import java.util.ArrayList;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.support.SessionStatus;
import org.springframework.web.servlet.ModelAndView;

import com.company.account.model.AccountForms;
import com.company.account.validator.AccountValidator;
import com.company.modelo.Entity.AccountEntity;
import com.company.modelo.service.AccountService;


@Controller
public class AccountController {

	@Autowired
	AccountService accountservice;
	
	AccountValidator accountValidator;
	
	@Autowired
	public AccountController(AccountValidator customerValidator){
		this.accountValidator = customerValidator;
	}
	
	@RequestMapping("/adminAccount.htm")
	public String initForm(ModelMap model){
		
		//Customer cust = new Customer();		
		//cust.setUserName("Ingrese Usuario");		
		//model.addAttribute("customer", cust);	
		List<AccountForms> milista = new ArrayList<AccountForms>();
		AccountForms obj;
		System.out.println("Antes de Recorrer");
		
		for (AccountEntity item : accountservice.AccountFinAll()) {
			obj=new AccountForms();
			obj.setId(item.getId());
			obj.setNumero(item.getNumero());
			obj.setNombre(item.getNombre());
			obj.setEstado(item.getEstado());
			obj.setBalance(item.getBalance());
			milista.add(obj);
			System.out.println(item.getId() + " - " + item.getNumero() + " - " + item.getNombre()+ " - " + item.getBalance() + " - " + item.getEstado());    
        }
		
		
		model.addAttribute("AccountList",milista);
		System.out.println("Retornando");
		return "AccountFormView";
		
		/*
		List<AccountForms> milista = new ArrayList<AccountForms>();
		AccountForms obj;
		System.out.println("Antes de Recorrer");
		for (int i=1; i<=10; i++)
		{
			obj=new AccountForms();
			obj.setNumero(Integer.toString(i));
			obj.setNombre(Integer.toString(i));
			obj.setEstado("Active");
			obj.setBalance("1500");
			milista.add(obj);
			System.out.println(Integer.toString(i));
		}
		model.addAttribute("AccountList",milista);
		System.out.println("Retornando");
		return "AccountFormView";*/
	}
	/*
	@RequestMapping(value = "/addAccount.htm", method = RequestMethod.POST)
    public String addContact(@ModelAttribute("AccountForms")
    AccountForms accountforms, BindingResult result) {
 
        //contactService.addContact(contact);
 
        return "AccountFormViewok";
    }*/
	
	//cuando inicializo para ir a la pantalla de nuevo
	    @RequestMapping(value="/addAccount",method = RequestMethod.GET)
		public ModelAndView AddAccountPage(){
	    	System.out.println("paso por aqui");
		   ModelAndView model = new ModelAndView("AccountFormViewAdd");
			AccountForms accountforms=new AccountForms(); 
			model.addObject("accountforms", accountforms);			
			return model;
		}
	    
	    //@RequestMapping("/ProcessAddAccount.htm")
	    @RequestMapping(value="/addAccount",method = RequestMethod.POST)
	    public ModelAndView AddAccount(@ModelAttribute("accountforms") AccountForms accountforms, BindingResult result, SessionStatus status){
	      
	    	accountValidator.validate(accountforms, result);
			
	    	   System.out.println(accountforms.getId().toString());
	    	   System.out.println(accountforms.getNumero());
			   System.out.println(accountforms.getNombre());
			   System.out.println(accountforms.getEstado());
			   System.out.println(accountforms.getBalance());
			   
			if (result.hasErrors()) {
				ModelAndView model = new ModelAndView("AccountFormViewAdd");
				return model;
			} else {

				AccountEntity obj=new AccountEntity();
				obj.setNumero(accountforms.getNumero());
				obj.setNombre(accountforms.getNombre());
				obj.setBalance(accountforms.getBalance());
				obj.setEstado(accountforms.getEstado());
				
				accountservice.SaveAccountAdd(obj);
				
				ModelAndView model = new ModelAndView("AccountFormViewok");			
				model.addObject("dedondevengo", "label.account.addaccount");	
				model.addObject("Mensaje", "La operacion de alta se realizo de forma exitosa con el numero xxx");	
			    return model;
			}
			
		   
		}
	    
	
		//cuando inicializo para ir a la pantalla de nuevo
				@RequestMapping(value="/EditAccount",method = RequestMethod.GET)
				public String initFormEdit(@RequestParam("Id_Account") String Id_Account, ModelMap model){
					System.out.println(Id_Account);					
					AccountEntity objAccountSearch = null;
					objAccountSearch = accountservice.findById(Integer.parseInt(Id_Account));					
					AccountForms accountforms=new AccountForms();
					accountforms.setId(objAccountSearch.getId());
					accountforms.setNumero(objAccountSearch.getNumero());
					accountforms.setNombre(objAccountSearch.getNombre());
					accountforms.setEstado(objAccountSearch.getEstado());
					accountforms.setBalance(objAccountSearch.getBalance());					
					model.addAttribute("accountforms", accountforms);
					return "AccountFormViewEddit";
				}
				
				
				@RequestMapping(value="/EditAccount",method = RequestMethod.POST)
			    public ModelAndView EditAccount(@ModelAttribute("accountforms") AccountForms accountforms, BindingResult result, SessionStatus status){			    		    	
				   
					accountValidator.validate(accountforms, result);
					
					
					
				   System.out.println(accountforms.getId().toString());
				   System.out.println(accountforms.getNumero());
				   System.out.println(accountforms.getNombre());
				   System.out.println(accountforms.getEstado());
				   System.out.println(accountforms.getBalance());
				   
				   if (result.hasErrors()) {
						ModelAndView model = new ModelAndView("AccountFormViewEddit");
						return model;
					} 
				   else 
					{
					    AccountEntity objAccountSearch = null;
						objAccountSearch = accountservice.findById(accountforms.getId());	
						objAccountSearch.setNumero(accountforms.getNumero());
						objAccountSearch.setNombre(accountforms.getNombre());
						objAccountSearch.setEstado(accountforms.getEstado());
						objAccountSearch.setBalance(accountforms.getBalance());
						
						accountservice.UpdateAccount(objAccountSearch);
						
					   ModelAndView model = new ModelAndView("AccountFormViewok");	
					   model.addObject("dedondevengo", "label.account.editaccount");	
					   model.addObject("Mensaje", "La operacion de Edicion se realizo de forma exitosa con el numero xxx");	
					   return model;
					}
				}
				
				
				//cuando inicializo para ir a la pantalla de nuevo
				@RequestMapping(value="/DelleteAllAccount.htm",method = RequestMethod.GET)
				public @ResponseBody String FormDeleteAll(@RequestParam("Id_AccountAll") String Id_AccountAll){
					System.out.println(Id_AccountAll);
					
					String[] result = Id_AccountAll.split("\\|");
					System.out.println(result.length);
			        for(String s : result){
			        	System.out.println(s);
			        	try {
							accountservice.DeleteAccount(Integer.parseInt(s));
						} catch (NumberFormatException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						} catch (Exception e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						}
			        }
			        
					 String returnText;					 
				     returnText = "Los Registros seleccionados fueron eliminados del medio de datos  " + Id_AccountAll;
				       
				        return returnText;				        
					
				}		
	           
}
